package com.m.pojo;

import javax.crypto.Cipher;
import java.security.*;

public class RSAPerson {
    String name;
    PrivateKey sk;
    PublicKey pk;

    public RSAPerson(String name) throws GeneralSecurityException {
        this.name = name;
        //生成公钥、私钥对
        KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");
        kpGen.initialize(1024);
        KeyPair kp = kpGen.generateKeyPair();
        this.sk = kp.getPrivate();
        this.pk = kp.getPublic();
    }
    //把私钥导出为字节
    public byte[] getPrivateKey() {
        return this.sk.getEncoded();
    }
    //把公钥导出为字节
    public byte[] getPublicKey() {
        return this.pk.getEncoded();
    }

    //用公钥加密
    public byte[] encrypt(byte[] message) throws GeneralSecurityException{
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, this.pk);
        return cipher.doFinal(message);
    }
    //用私钥解密
    public byte[] decrypt(byte[] input) throws GeneralSecurityException{
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, this.sk);
        return cipher.doFinal(input);
    }
}
